/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: manager.hpp
 */

#ifndef _MANAGER_HPP_
#define _MANAGER_HPP_

#include <iostream>
#include <string>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <exception>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <cstdlib>

#include "runner.hpp"
#include "workflow.hpp"
#include "wfqueue_manager.hpp"
#include "worker.hpp"
#include "worker_discovery.hpp"
#include "xml_syn_logging.hpp"

using namespace middleware::queueing;

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
/*! \struct ManagerConfig
 * \brief Configuration structure for Manager.
 *
 * Correctly configures a Manager.
 */
typedef struct {
	/*!
	 * Ip v4 address to bind to in order to listen for incoming TaskDescriptor
	 * sent by other peers' Manager.
	 */
	std::string man_ip_toman_bind; /* IP not used to bind to for UIs */
	/*!
	 * Port number to bind to in order to listen for incoming TaskDescriptor
	 * sent by other peers' Manager.
	 */
	std::string man_port_toman_bind; /* Port to bind to, to listen for UIs */
	/*!
	 * Pointer to Worker in order to enqueue TaskDescriptor.
	 */
	Worker* ptrto_worker; /* To enqueue a task */
	/*!
	 * Pointer to WorkerDiscovery in order to request for WorkerDescriptor
	 * when choosing which peer to sent a TaskDescriptor to.
	 */
	WorkerDiscovery* ptrto_discovery; /* To get worker */
	/*!
	 * Logger
	 */
	logging::XmlSynLogger* _xml_logger;
} ManagerConfig;
}
// Constants
//-----------------------------------------------------------------------------
namespace middleware {
/*!
 * Lowest port number to which the Manager will listen for incoming
 * TaskDescriptors.
 */
const unsigned int kManagerMinManPort = 1051;
/*!
 * Highest port number to which the Manager will listen for incoming
 * TaskDescriptors.
 */
const unsigned int kManagerMaxManPort = 65536 - 1;
/*!
 * Etiquette for output.
 */
const std::string kManagerEtq = "MAN:       ";
/*!
 * Etiquette for output.
 */
const std::string kManager1Etq = "TaskManager:               ";
}
//-----------------------------------------------------------------------------
// Class definitions
namespace middleware {
/*! \class Manager
 * \brief Represents the Manager of the peer.
 *
 * Manager is charged to provide logic and functionalities in order to
 * correctly route a TaskDescriptor when arriving from its UI inside a well
 * provided Workflow. Manager also listens for incoming TaskDescriptor from
 * the outside, in this case, Manager will redirect them directly to the peer's
 * Worker enqueueing it. Manager has to dialogue with WorkerDiscovery in order
 * to know which Worker is the best one to send the TaskDescriptor to.
 */
class Manager : public Runner {
	/*!
	 * To let the proxy operate correctly.
	 */
	friend class WFQueueManagerProxy;
public:
	/*!
	 * Constructs a non configured Manager. Resulting Manager will bind to
	 * loopback address on a casual port. Pointers to Worker and
	 * WorkerDiscovery are initialized to zero.
	 */
	Manager();
	/*!
	 * Constructs a new Manager and configuring it with a ManagerConfig object.
	 * \param conf The configuration structure for the Manager.
	 */
	Manager(ManagerConfig conf);
	/*!
	 * Destroy Manager.
	 */
	~Manager();
	/*!
	 * Runs Manager. If another thread was running, it will be destoyed.
	 */
	void run() {
		this->_manager_thread.reset();
		this->_manager_thread = boost::shared_ptr<boost::thread>(
				new boost::thread(
						boost::bind(&Manager::exec, this)));
	}
	/*!
	 * Joins to this thread and wait for it to finish. When calling run(), user
	 * should immediately call this function in order to let the current thread
	 * not to die and terminate child.
	 */
	void join() {
		(this->_manager_thread)->join();
	}
private:
	/*!
	 * Creates a casual port number > 1050 and gets it.
	 */
	std::string createPort();
	/*!
	 * Execution function.
	 */
	void exec();
	/*!
	 * Execution function for task manager.
	 */
	void exec_taskmanager();
	/*!
	 * Enqueues workflows when asked locally by UI.
	 */
	void enqueuer(const Workflow& wf);
	/*!
	 * After that Manager gets a workflow, it must deal with it in order to
	 * route it to the correct workers. This is a thread execution flow.
	 */
	void ManageWorkflow(Workflow workflow);
	/*!
	 * Initialization routine with user.
	 */
	void bonjour();
	/*!
	 * Configuration.
	 */
	ManagerConfig _config;
	/*!
	 * Undrlaying thread. This thread is responsible for managing Manager
	 * activity, it also dequeues elements from the main queue.
	 */
	boost::shared_ptr<boost::thread> _manager_thread;
	/*!
	 * This thread is responsible for listening to incoming tasks and "send"
	 * them to the underlaying worker in this peer.
	 */
	boost::shared_ptr<boost::thread> _taskmanager_thread;
	/*!
	 * Shared queue of workflows.
	 */
	WFQueueManager _wfqueue_manager;
}; /* UI */
} /* middleware */

#endif
